import type { Directive, DirectiveBinding } from 'vue'
import { isString } from 'lodash'
/**
 * 权限指令
 */
export const auth: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const { value } = binding
    if (value[0] === undefined)
      return
    if (value) {
      if (el instanceof HTMLButtonElement || el instanceof HTMLInputElement) {
        // 启用或禁用按钮
        if (!hasAuth(value)) {
          el.remove()
        }
      }
    }
    else {
      throw new Error('[Directive: auth]: need auths! Like v-auth="[\'btn.add\',\'btn.edit\']"')
    }
  },
}

/** 是否有按钮级别的权限 */
function hasAuth(value: string | Array<string>): boolean {
  if (!value)
    return false
  if (value === 'undefined')
    return true
  if (isString(value)) {
    return useUserStoreHook().user?.permsList?.includes(value) ?? false
  }
  return isIncludeAllChildren(value, useUserStoreHook().user?.permsList ?? [])
}

/** 是否包含全部的权限 */
function isIncludeAllChildren(value: string[], permsList: string[]) {
  // 使用 every 方法检查 value 中的每个元素是否都在 metaAuths 中
  return value.every(v => permsList.includes(v))
}
